﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using VMDS.Business.Processes;

namespace VMDS.GUIClient.Model
{
    class Deployer:INotifyPropertyChanged
    {
        public Deployer()
        {
            MsgCopyError = "Ошибка копирования";
            MsgServiceConnectError = "Ошибка подключения к сервису";
            MsgStorageError = "Хранилище недоступно";
            MsgZipError = "Ошибка архивирования";
            MsgCopying = "Копирование...";
            MsgTempClear = "Удаление временных файлов";
            MsgZipping = "Архивируется ";
        }
        
        public string MsgServiceConnectError { get; set;  }
        public string MsgStorageError { get; set; }
        public string MsgCopyError { get; set; }
        public string MsgZipError { get; set; }
        public string MsgCopying { get; set; }
        public string MsgTempClear { get; set; }
        public string MsgZipping { get; set; }
        
        
        public string SubDirectory { get; set; }
        public string TargetName { get; set; }
        public string LocalPath { get; set; }
        public string CacheDirectory { get; set; }

        private string _opmsg;
        public string OperMessage
        {
            get { return _opmsg; }
            set { _opmsg = value;
                OnProp("OperMessage");
            }
        }

        private int _opprog;
        public int OperProgress
        {
            get { return _opprog; }
            set { _opprog = value;
                OnProp("OperProgress");
            }
        }
        static bool CheckShare(string unc,string targetName)
        {
            if (!string.IsNullOrWhiteSpace(unc))
            {
                if (Directory.Exists(unc))
                       Directory.CreateDirectory(unc + "\\" + targetName);
                        return true;
                   
            } 
            return false;
        }

        static bool ZipRequired(string path)
        {
            return new FileInfo(path).Extension.ToLower() != ".zip";
        }


        public void Start()
        {
            
            string share = ServiceLocator.MainService.GetShareUNC() + "\\"+SubDirectory;
            if (!CheckShare(share,TargetName))
            {
                OperMessage = MsgStorageError;
                return;
            }
            string newpath = "";
            string local = LocalPath;
            var zipneed = ZipRequired(LocalPath);
            if (zipneed)
            {
                FastZip compressor;
                FastZipEvents events = new FastZipEvents();
                local = CacheDirectory+"\\" + Guid.NewGuid() + ".zip";
                events.Progress += new ProgressHandler(events_Progress);
                events.ProcessFile += new ProcessFileHandler(events_ProcessFile);
                events.ProgressInterval = TimeSpan.FromMilliseconds(500);
                compressor = new FastZip(events);
                try
                {
                    compressor.CreateZip(local, new FileInfo(LocalPath).DirectoryName, true, null, null);
                }
                catch (Exception)
                {
                    OperMessage =MsgZipError ;
                    if (File.Exists(local)) File.Delete(local);
                    throw;
                    
                }
            }
            OperMessage = MsgCopying;
            var copier = new FileCopier();
            newpath = share + "\\" + TargetName + "\\"+SubDirectory+".zip";
            copier.CopyProgress += new CopyProgressEventHandler(copier_CopyProgress);
            try
            {
                copier.CopyFile(local, newpath);
            }
            catch (Exception)
            {
                OperMessage = MsgCopyError;
                return;
            }
            if (zipneed)
            {
                OperMessage = MsgTempClear;
                File.Delete(local);
            }
            
        }
        void events_ProcessFile(object sender, ScanEventArgs e)
        {
            string s = new FileInfo(e.Name).Name;
            OperMessage = MsgZipping + s;
        }

        void events_Progress(object sender, ProgressEventArgs e)
        {
            OperProgress = Convert.ToInt32(e.PercentComplete);
        }

        void copier_CopyProgress(object sender, CopyProgressEventArgs e)
        {
            OperProgress = (int)(e.TotalBytesTransferred * 100 / e.TotalFileSize);
        }
       
        #region Implementation of INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;
        void OnProp(string name)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
        #endregion
        
    }
}
